//
//  NYExamineTestViewController.m
//  NiuWaJiaoYu
//
//  Created by 袁航 on 2018/1/9.
//  Copyright © 2018年 niuwaketang. All rights reserved.
//

#import "NYExamineTestViewController.h"
#import "NYSubjectTitleCell.h"
#import "NYSubjectAnswerCell.h"
#import "NYExamineTestActionCell.h"
#import "NYExamineTestTextViewCell.h"
#import "NYAirlineViewController.h"
#import "NYExamineSubmitRequest.h"
#import "NYExamineTestSubmitSuccessViewController.h"
#import "NYMyExamineDetailViewController.h"
#import "NYExamineTestSectionTitltHeader.h"
#import "NYExamineTestMsgSectionHeader.h"
//request
#import "NYLeaveMessageRequest.h"
#import "NYExamineTestRequest.h"
#import "NYAddToGoodSubjectRequest.h"

@interface NYExamineTestViewController ()
@property(nonatomic, strong) NYExamineTestListModel *listModel;
@property(nonatomic, strong) NYExamineTestRequest *request;
@property(nonatomic, strong) NSString *examine_id;
@property(nonatomic, assign) NYExamineRequestStatus status;

@end

@implementation NYExamineTestViewController

- (instancetype)initWithExamineRequestStatus:(NYExamineRequestStatus)status
                                 withExamineID:(NSString *)examine_id {
        
        self = [super initWithStyle:UITableViewStyleGrouped];
        if (self) {
                self.status = status;
                self.examine_id = examine_id;
        }
        return self;
}

- (instancetype)initWithStyle:(UITableViewStyle)style
{
        return [super initWithStyle:UITableViewStyleGrouped];
}
- (void)viewDidLoad
{
        [super viewDidLoad];
        [self.tableView registerClass:[NYExamineTestMsgSectionHeader class] forHeaderFooterViewReuseIdentifier:[NYExamineTestMsgSectionHeader className]];
        [self.tableView registerClass:[NYExamineTestSectionTitltHeader class] forHeaderFooterViewReuseIdentifier:[NYExamineTestSectionTitltHeader className]];
        [self.tableView registerClass:[BaseTableHeaderFooterView class] forHeaderFooterViewReuseIdentifier:[BaseTableHeaderFooterView className]];
        [self loadData];
}
- (void)initSubviews
{
        [super initSubviews];
        
        self.controllerView.status = _status;
        @weakify(self);
        self.controllerView.actionBlock = ^(NYExamineTestViewActionType actionType) {
                @strongify(self);
                switch (actionType) {
                        case NYExamineTestViewActionTypeJumpToMsg:
                        {
                                [self showCommentViewWithCleanText:NO];
                        }
                                break;
                        case NYExamineTestViewActionTypeSubmit:
                        {
                                [self configAnswerAndSubmit];
                        }
                                break;
                        default:
                                break;
                }
        };
}

/**
 /// 点击发送按钮的回调

 @param commentView 评论框
 @param hideBlock 网络请求后，隐藏调用
 @param cleanTextBlock 网络请求后，清理输入框文字调用
 */
- (void)commentViewSendButtonDidClick:(id<BaseCommentToolBarProtocol>)commentView hideBlock:(void (^)(BOOL))hideBlock cleanTextBlock:(void (^)(BOOL))cleanTextBlock
{

        NSString *type_id = (_status == NYExamineRequestStatusChoose) ? @"1" : @"2";
        [[NYLeaveMessageRequest requestWithParams:@{
                                                    kRequestKeyTypeID :type_id,
                                                    kRequestKeyExamineID : NOT_NULL_STRING_DEFAULT_EMPTY(self.examine_id),
                                                    kRequestKeyContent :                                                      NOT_NULL_STRING_DEFAULT_EMPTY(commentView.text),

                                                    }] startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof id  _Nonnull data) {
                [NYTipClass showText:@"留言成功"];
                [self hideCommentViewWithCleanText:true force:true];

        } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {
                
//                [self hideCommentViewWithCleanText:false force:true];
        }];
}
- (void)loadData
{
        [self setLoading:YES animation:YES];
        [self configNimbus];
        
        NSDictionary *paraDict = @{};
        if (_status == NYExamineRequestStatusChoose) {
                paraDict = @{kRequestKeyExaminationID : NOT_NULL_STRING_DEFAULT_EMPTY(self.examine_id)};
        } else {
                paraDict = @{kRequestKeyExamineID : NOT_NULL_STRING_DEFAULT_EMPTY(self.examine_id)};
        }

        self.request = [NYExamineTestRequest requestWithType:_status param:paraDict];
        [self.request startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof NYExamineTestListModel * _Nonnull data) {
                self.listModel = data;
                self.controllerView.testListModel = data;
                [self configNimbusDataForMutableSections:data];
                [self setSuccess];
        } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {
                [self setError:error];
        }];
}
- (UITableViewCell *)tableViewModel:(NITableViewModel *)tableViewModel cellForTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath withObject:(id)object
{
        
        UITableViewCell *cell = [super tableViewModel:tableViewModel cellForTableView:tableView atIndexPath:indexPath withObject:object];
        if ([cell isKindOfClass:[NYExamineTestActionCell class]]) {
                [self configActionCell:(NYExamineTestActionCell *)cell];
        }
        return cell;
}
- (void)configActionCell:(NYExamineTestActionCell *)actionCell
{
        @weakify(self);
        @weakify(actionCell);
        [actionCell setActionBlock:^(NYExamineTestActionType actionType,  NYSubjectModel *questionModel) {
                @strongify(self);
                @strongify(actionCell);
                switch (actionType) {
                        case NYExamineTestActionTypeAnalysis:
                        {
                                
                                NYSubjectAnalysisType type;
                                if (self.status == NYExamineRequestStatusCup) {

                                        type = NYSubjectAnalysisTypeCutGame;
                                } else if (self.status == NYExamineRequestStatusChoose) {
                                        
                                        type = NYSubjectAnalysisTypeExaminationAnalysis;
                                } else {
                                        type = NYSubjectAnalysisTypeExamine;
                                }
                                [self routeUrl:kNYSubjectAnalysisURI param:@{
                                                                             kRequestKeyType : @(type),
                                                                             kRequestKeyTypeID : NOT_NULL_STRING_DEFAULT_EMPTY(questionModel.id)
                                                                             }];
                        }
                                break;
                        case NYExamineTestActionTypeAddToGood:
                        {
                                [[NYAddToGoodSubjectRequest requestWithParams:@{
                                                                                kRequestKeyExercisesId : NOT_NULL_STRING_DEFAULT_EMPTY(questionModel.id),
                                                                                kRequestKeyTypeID : @(questionModel.genre?: NYGenreTypeExamination),
                                                                                }] startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof NSString * _Nonnull data) {
                                        [NYTipClass showText:request.tipString inView:self.view];
                                        questionModel.is_good = @"2";
                                        [self.tableView reloadRowAtIndexPath:[self.tableView indexPathForCell:actionCell] withRowAnimation:(UITableViewRowAnimationNone)];
                                } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {
                                        [NYTipClass showErrorWithText:error.localizedDescription inView:self.view];
                                }];
                        }
                                break;
                                
                        default:
                                break;
                }
                
        }];
}

- (void)jumpToDetailController:(NYExamineSubmitResModel * )data
{
        [self.request clearCache];
        NYMyExamineDetailViewController *vc = [[NYMyExamineDetailViewController alloc] init];
        
        NYMyExamineDetailModel *detailModel = [[NYMyExamineDetailModel alloc] init];
        detailModel.page_info = data.page_info;
        detailModel.score_statistics = data.score_statistics;
        detailModel.results = [data.results sortedArrayUsingComparator:^NSComparisonResult(NYMyExamineResultModel *  _Nonnull obj1, NYMyExamineResultModel *  _Nonnull obj2) {
                return obj1.num.integerValue > obj2.num.integerValue;
        }];
        vc.analysisType = NYSubjectAnalysisTypeExamine;
        switch (self.status)
        {
                case NYExamineRequestStatusCup:
                {
                        vc.analysisType = NYSubjectAnalysisTypeCutGame;
                }
                        break;
                case NYExamineRequestStatusTest:
                {
                        vc.analysisType = NYSubjectAnalysisTypeExamine;
                }
                        break;
                case NYExamineRequestStatusChoose:
                {
                        vc.analysisType = NYSubjectAnalysisTypeExaminationAnalysis;
                }
                        break;
                        
                default:
                        break;
        }
        
        vc.detailModel = detailModel;
        NSMutableArray *navControllers = [NSMutableArray arrayWithObject:self.navigationController.viewControllers.firstObject];
        [navControllers addObject:vc];
        [self.navigationController setViewControllers:navControllers animated:YES];
}
- (void)jumpToSuccessController
{
        NYExamineTestSubmitSuccessViewController *vc = [[NYExamineTestSubmitSuccessViewController alloc] init];
        NSMutableArray *navControllers = [NSMutableArray arrayWithObject:self.navigationController.viewControllers.firstObject];
        [navControllers addObject:vc];
        [self.navigationController setViewControllers:navControllers animated:YES];
}
- (void)configAnswerAndSubmit
{
        [NYTipClass showLoadingInView:self.view];
        NSMutableDictionary <NSString *, NSString *>*answerDict = @{}.mutableCopy;
        NSMutableDictionary <NSString *,NSIndexPath *>*unAnswerDict = @{}.mutableCopy;
        [self.listModel.ex_list enumerateObjectsUsingBlock:^( NYSubjectModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (obj.user_answer != nil)
                {
                        [answerDict setObject:obj.user_answer forKey:[NSString stringWithFormat:@"answer%d",(int)idx+1]];
                }
        }];
        [self configUnAnswerQuestionAnswerDict:answerDict unAnswerDict:unAnswerDict];
        
}
- (void)configUnAnswerQuestionAnswerDict:(NSMutableDictionary <NSString *, NSString *>*)answerDict unAnswerDict:(NSMutableDictionary <NSString *,NSIndexPath *>*)unAnswerDict
{
                if (answerDict.count == self.listModel.ex_list.count)
                {
                        /// 提交答案
                        [[NYExamineSubmitRequest requestWithType:self.status param:@{
                                kRequestKeyExamineID : self.listModel.id,
                                @"answer" : answerDict.jsonStringEncoded,
                                @"when" : [self.controllerView usedTime]
                        }] startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof NYExamineSubmitResModel * _Nonnull data) {
                                
                                [NYTipClass hideLoadingInView:self.view];
                                [self jumpToDetailController:data];
                        } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {
                                [NYTipClass hideLoadingInView:self.view];
                                [NYTipClass showText:error.localizedDescription inView:self.view];
                        }];
                }
                else
                {
                        [NYTipClass showText:@"您有答案未填写，请完成后提交" inView:self.view];
                }
}

- (void)configChoiceAnswer:( NYSubjectModel *)subjectObj atIndexPath:(NSIndexPath *)indexPath
{
        if (subjectObj.question_type != NYQuestionTypeFillBlanks)
        {
                subjectObj.user_answer = nil;
                NSMutableArray *resArr = @[].mutableCopy;
                [self.tableView.indexPathsForSelectedRows enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        if (obj.section == indexPath.section)
                        {
                                [resArr addObject:@(obj.row).stringValue];
                        }
                }];
                subjectObj.user_answer = resArr;
        }
        
}
/// MARK: - TableVie
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
        id obja = [self.tableViewModel objectAtIndexPath:indexPath];
        if ([obja isKindOfClass:[NICellObject class]]) {
                NICellObject *obj = [self.tableViewModel objectAtIndexPath:indexPath];
                [self configChoiceAnswer:obj.userInfo atIndexPath:indexPath];
        }
        
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
       id obja = [self.tableViewModel objectAtIndexPath:indexPath];
        if ([obja isKindOfClass:[NICellObject class]]) {
                NICellObject *obj = [self.tableViewModel objectAtIndexPath:indexPath];
                [self configChoiceAnswer:obj.userInfo atIndexPath:indexPath];
        }
        
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
        if ([self.tableViewModel numberOfSection] - 2 == section) {
                return __WGHeight(10);
        }
        if (@available(iOS 11, *))
        {
                return CGFLOAT_MIN;
        }
        return 0.0001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
        if (section == 0 && !NULLString(self.listModel.ex_title))
        {
                return __WGHeight(70);
        }
        if ([self.tableViewModel numberOfSection] - 1 == section) {
                return __WGHeight(41);
        }
        if (@available(iOS 11, *)) {
                return CGFLOAT_MIN;
        }
        return 0.0001;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
        if (section == 0) {
                NYExamineTestSectionTitltHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:[NYExamineTestSectionTitltHeader className]];
                header.testListModel = self.listModel;
                return header;
        } else if ([self.tableViewModel numberOfSection] - 1 == section) {
                NYExamineTestMsgSectionHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:[NYExamineTestMsgSectionHeader className]];
                return header;
        }
        return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
        BaseTableHeaderFooterView *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:[BaseTableHeaderFooterView className]];
        footer.contentView.backgroundColor = UIColorForBackground;
        return footer;
}

- (void)configNimbus
{
        [super configNimbus];
        [self.tableViewActions forwardingTo:self.controllerView];
        @weakify(self);
        [self.tableViewActions attachToClass:[NICellObject class] tapBlock:^BOOL(NICellObject * object, NYExamineTestViewController * target, NSIndexPath *indexPath) {
                @strongify(self);
                NYSubjectModel *subjectObj = object.userInfo;
                /// return YES 会调用 deselectRowAtIndexPath 方法， return NO 则不会调用
                /// 标题
                if (indexPath.row == 0)
                {
                        return YES;
                }
                /// 填空题
                if (subjectObj.question_type == NYQuestionTypeFillBlanks)
                {
                        return YES;
                }
                
                /// 每组最后一个 actionCell
                /// 已做过，才会出现查看解析，或者加入好题本 的 actionCell
                if (subjectObj.is_test.integerValue == 2 && indexPath.row + 1 == [target.tableViewModel countInSection:indexPath.section])
                {
                        return YES;
                }
                /// 单项选择题
                if (subjectObj.question_type == NYQuestionTypeSingleChoice)
                {
                        /// 判断当前是否有选项选择
                        [target.tableView.indexPathsForVisibleRows enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                                if (obj.section == indexPath.section && obj.row != indexPath.row)
                                {
                                        [target.tableView deselectRowAtIndexPath:obj animated:NO];
                                }
                        }];
                        return NO;
                }
                /// 多选题
                return NO;
        }];
}
- (void)configNimbusDataForMutableSections:(NYExamineTestListModel *)data
{
        [data.ex_list enumerateObjectsUsingBlock:^( NYSubjectModel * _Nonnull subjectObj, NSUInteger subjectIdx, BOOL * _Nonnull subjectStop) {
                if (NULLString(subjectObj.is_test)) {
                        subjectObj.is_test = data.is_test.copy;
                }
                [self.tableViewModel addSectionWithTitle:nil];
                [self.tableViewModel addObject:[NICellObject objectWithCellClass:[NYSubjectTitleCell class] userInfo:subjectObj]];
                if (subjectObj.question_type != NYQuestionTypeFillBlanks) {
                        [subjectObj.exercises_answer_arr enumerateObjectsUsingBlock:^(NSString * _Nonnull daanObj, NSUInteger daanIdx, BOOL * _Nonnull daanStop) {
                                [self.tableViewModel addObject:[NICellObject objectWithCellClass:[NYSubjectAnswerCell class] userInfo:subjectObj]];
                        }];
                }
                else
                {
                        [self.tableViewModel addObject:[NICellObject objectWithCellClass:[NYExamineTestTextViewCell class] userInfo:subjectObj]];
                }
                /// 已做过，才会出现查看解析，或者加入好题本
                if (subjectObj.is_test.integerValue == 2)
                {
                        [self.tableViewModel addObject:[NICellObject objectWithCellClass:[NYExamineTestActionCell class] userInfo:subjectObj]];
                }
        }];
        /// 消息列表
        [self.tableViewModel addSectionWithTitle:nil];
        [self.tableViewModel addObjectsFromArray:data.message_list];
        [self.tableView reloadData];
}

- (void)configNavigationBar:(BaseNavigationBar *)navigationBar
{
        [super configNavigationBar:navigationBar];
        self.title = @"考试";
}

/**
 返回对应评论框类型

 @return 暂时用这个吧，自动增加行高的不能用了
 */
- (BaseCommentToolBarType)commentToolBarType
{
        return BaseCommentToolBarTypeNormal;
}
+ (NYViewControllerNavigationBarType)navigationBarType
{
        return NYViewControllerNavigationBarTypeBlue;
}
@end
